package com.itheima.proxy;

import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import com.itheima.service.impl.DeptServiceImpl2;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 创建JDK代理对象的工厂
 *
 * @author GY
 * @version V1.0
 * @date 2025-01-17 15:40
 */
@Slf4j
public class JdkProxyFactory {

    public static DeptService createProxy(DeptService target) {
        /*
         * ClassLoader loader 和目标对象相同的类加载器
         * Class<?>[] interfaces 和目标对象相同的接口Class列表
         * InvocationHandler 如何代理
         */
        return (DeptService) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if ("toString".equals(method.getName())){
                            return null;
                        }
                        long begin = System.currentTimeMillis();
                        Object result = method.invoke(target, args);
                        long end = System.currentTimeMillis();
                        log.info("执行耗时:{}", (end - begin));
                        return result;
                    }
                }
        );
    }

    public static void main(String[] args) {
        DeptService target = new DeptServiceImpl2();
        DeptService proxy = JdkProxyFactory.createProxy(target);
        proxy.queryAll();
        Dept dept= new Dept();
        proxy.insert(dept);
    }



}
